//
//  FindPathSecondViewController.m
//  
//
//  Created by 郭明皓 on 15/10/29.
//
//

#import "FindPathSecondViewController.h"
#import <AFNetworking.h>
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "GMHPath.h"
#import "FindPathSecondCell.h"
#import "FindPathSecondAnotherCell.h"
#import "FindPathThirdViewController.h"
#import "GMHDataFiled.h"
#import "DKNightVersion.h"
@interface FindPathSecondViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *trailsArr;
@property (nonatomic, assign)NSInteger pageIndex;
@property (nonatomic, assign)BOOL isUpPull;
@end

@implementation FindPathSecondViewController
- (void)dealloc
{
    [_trailsArr release];
    [_tableView release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.trailsArr = [NSMutableArray array];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height + 49) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView release];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 150;
    
    self.tableView.nightBackgroundColor = [UIColor blackColor];
    self.tableView.nightSeparatorColor = [UIColor darkGrayColor];
    
    [self DownPull];
    [self UpPull];
    
}
- (void)DownPull
{
    __block FindPathSecondViewController *find = self;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.tableView.footer endRefreshing];
        self.pageIndex = 1;
        self.isUpPull = NO;
        [find createData];
    }];
    [self.tableView.header beginRefreshing];
}
- (void)UpPull
{
    __block FindPathSecondViewController *find = self;
    self.tableView.footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        self.pageIndex++;
        self.isUpPull = YES;
        [find createData];
    }];
    
}
- (void)createData
{
    [GMHDataFiled isHaveFileDocument];
    [GMHDataFiled isHaveFileFind];
    NSString *strurl = [NSString stringWithFormat:@"http://tubu.ibuzhai.com/rest/v2/trails?&device_type=2&area_id=&app_version=4.3.4&api_version=1&access_token=&page_size=20&search=%@&search_in=1&page=%ld", self.provinceName, _pageIndex];
    if (_isUpPull == NO) {
        [self.trailsArr removeAllObjects];
    }
//    转化为数字编码
    NSString *strs = [strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager GET:strs parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = responseObject;
        NSMutableArray *arr = [GMHPath baseModelArry:dic[@"trails"]];
        [self.trailsArr addObjectsFromArray:arr];
        if (_trailsArr.count > 0 ) {
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
        
        NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Find/PathTitle.plist"];
        [NSKeyedArchiver archiveRootObject:dic toFile:CachesPath];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"获取失败");
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.trailsArr.count < 4) {
        tableView.backgroundColor = [UIColor clearColor];
    }
    return self.trailsArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.trailsArr.count != 0) {
        GMHPath *path = self.trailsArr[indexPath.row];
        NSInteger number = [path.activity_count integerValue];
        if (number != 0) {
            static NSString *strs = @"secondPath";
            FindPathSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
            if (!cell) {
                cell = [[FindPathSecondCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strs];
            }
            [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉分割线
            [cell.images sd_setImageWithURL:[NSURL URLWithString:path.cover]placeholderImage:[UIImage imageNamed:@"travel.jpg"]];
            cell.nameLabel.text = path.name;
            cell.destination.text = path.destination;
            cell.countLabel.text = [NSString stringWithFormat:@"%@个活动", path.activity_count];
            
            return cell;
            
        }
        else
        {
            static NSString *strs = @"another";
            FindPathSecondAnotherCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
            if (!cell) {
                cell = [[FindPathSecondAnotherCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strs];
            }
            [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];//去掉分割线
            
            [cell.images sd_setImageWithURL:[NSURL URLWithString:path.cover]placeholderImage:[UIImage imageNamed:@"travel.jpg"]];
            cell.nameLabel.text = path.name;
            cell.destination.text = path.destination;
            return cell;
        }

    }
    else
    {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//返回后 没有灰色图案
    FindPathThirdViewController *third = [[FindPathThirdViewController alloc]init];
    [self.navigationController pushViewController:third animated:YES];
    [third release];
    GMHPath *paths = self.trailsArr[indexPath.row];
   
    third.number = paths.id;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
